package com.social.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.social.dao.LogDao;

@WebServlet("/deleteLog")
public class DeleteLogServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置响应格式
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 获取日志ID
        String logId = request.getParameter("id");
        if (logId == null || logId.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(new Gson().toJson(
                    new Response(false, "日志ID不能为空")));
            return;
        }

        try {
            // 将ID转换int类型
            int id = Integer.parseInt(logId);

            LogDao l = new LogDao();
            // 调用数据库删除方法
            int success = l.deleteLog(id);

            if (success == 1) {
                response.getWriter().write(new Gson().toJson(
                        new Response(true, "日志删除成功")));
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write(new Gson().toJson(
                        new Response(false, "删除日志失败")));
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(new Gson().toJson(
                    new Response(false, "无效的日志ID")));
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write(new Gson().toJson(
                    new Response(false, "服务器错误: " + e.getMessage())));
        }
    }



    // 内部类用于JSON响应
    private static class Response {
        private boolean success;
        private String message;

        public Response(boolean success, String message) {
            this.success = success;
            this.message = message;
        }

        // getters for Gson
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
    }
}